<template>
  <div class="h5-container h5-send">
    <NavBar title="我的工作" :onClickLeft="toBack"></NavBar>

    <div class="h5-filter">
      <van-dropdown-menu active-color="#1989fa" direction="down" >
        <van-dropdown-item @change="changeTenant" :title="filterTitle" v-model="currentTenant" :options="tenants" >
        </van-dropdown-item>
      </van-dropdown-menu>
    </div>

    <div class="send-body">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      class="list-wrapper"
      v-if="!empty"
      :offset="20"
      @load="load"
    >
      <van-cell v-for="item in list" :key="item.id" class="send-cell" >
      <div class="send-cell-title">{{ item.tenantName }}

        <van-tag mark size="medium" :type="item.status" style="margin-left:5px;">{{item.status | statusText}}</van-tag>
        <span v-if="item.status === 'success'">
          <i class="el-icon-time" style="margin-left:5px;" />
          <span class="font-14 remain-text"><van-icon name="clock-o" style="margin-right:2px;" />{{item.endTime|timeRemain}}</span>
        </span>
      </div>
      <div class="send-cell-date">服务时间：{{ item.startTime | timeFilter }} ~ {{ item.endTime | timeFilter }}</div>

      </van-cell>
    </van-list>
    <van-empty description="暂无工作记录" v-if="empty" />
    </div>

  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { getSendList } from '@common/api/send';
import { getWorkerTenants } from '@common/api/worker';
import { formatTime } from '@common/utils/time';
import moment from 'moment';
import NavBar from './components/NavBar';
export default {
  filters: {
    timeFilter(time) {
      if (time) return formatTime(time, { format: 'YYYY-MM-DD HH:mm' });
      return '--';
    },
    timeRemain(endTime) {
      const remainTime = Math.ceil((moment(endTime) - moment(new Date())) / (1000 * 60 * 60 * 24));
      if (remainTime > 0) return `剩余${remainTime}天`;
      return '';
    },
    statusText(status) {
      if (status === 'success') {
        return '服务中';
      } if (status === 'over') {
        return '已结束';
      }
      return '未开始';
    },
  },
  components: {
    NavBar,
  },
  data() {
    return {
      list: [],
      limit: 10,
      currentPage: 1,
      loading: true, // 派遣记录loading
      totalCount: 0, // 派遣记录总数
      finished: false,
      tenants: [{ text: '所有单位', value: 'ALL' }],
      currentTenant: 'ALL',
    };
  },
  computed: {
    ...mapGetters(['token']),
    empty() {
      return this.loading === false && this.totalCount === 0;
    },
    filterTitle() {
      if (this.currentTenant) {
        return this.tenants.find(v => v.value === this.currentTenant)?.name;
      }
      return '所有单位';
    },
  },
  created() {
    this.fetchSendList();
    this.getTenants();
  },
  methods: {
    toBack() {
      this.$router.push({
        path: '/',
      });
    },
    async fetchSendList(currentPage, tenantId) {
      currentPage = currentPage || this.currentPage;
      const params = {
        limit: this.limit,
        offset: (currentPage - 1) * this.limit,
        workerId: this.token,
        needTenantInfo: true,
      };
      if (tenantId && tenantId !== 'ALL') {
        params.tenantId = tenantId;
      }
      try {
        const sendRes = await getSendList(params);
        this.handleRenderList(sendRes?.data?.list || [], 1);
        this.totalCount = sendRes?.data?.totalCount || 0;
        this.finished = sendRes?.data?.list?.length < this.limit;
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    async getTenants() {
      const workerTenants = await getWorkerTenants({
        workerId: this.token,
      });
      this.tenants = this.tenants.concat(workerTenants.list.map(v => ({
        text: v.name,
        value: v.id,
      })));
    },
    // load
    async load() {
      this.loading = true;
      this.currentPage = this.currentPage + 1;
      try {
        const sendInfo = await getSendList({
          offset: (this.currentPage - 1) * this.limit,
          limit: this.limit,
          needTenantInfo: true,
          workerId: this.token,
        });
        this.handleRenderList(sendInfo?.data?.list || [], this.currentPage);
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.currentPage = this.currentPage - 1;
        this.finished = false;
      }
    },
    handleRenderList(list, page) {
      const now = new Date();
      list.forEach(v => {
        if (Math.ceil(moment(v.startTime) - moment(now) > 0)) { // 未开始
          v.status = 'primary';
        } else if (Math.ceil(moment(v.endTime) - moment(now) > 0)) { // 服务中
          v.status = 'success';
        } else { // 已结束
          v.status = 'over';
        }
      });
      if (page === 1) {
        this.list = list;
      } else {
        this.list = this.list.concat(list);
      }
      this.finished = this.list.length <= this.totalCount;
    },
    // 切换用工单位
    changeTenant(value) {
      this.currentTenant = value;
      this.fetchSendList(1, value);
    },
  },
};
</script>
<style lang="scss" scoped>
.h5-send {
  position: relative;
  width: 100%;
  height: 100vh;
  .send-body {
    position: relative;
    width: 100%;
    padding-top: 190px;
    // .list-wrapper{
    //   margin-top: 100px;
    // }
   .van-tag--over{
     background-color: #ccc;
   }

   .remain-text{
     font-weight: normal;
   }
    .send-cell {
      .send-cell-title {
        font-weight: bold;
        line-height: 50px;
        margin-bottom: 10px;
      }
      .send-cell-date {
        font-size: 24px;
        color: #666;
      }
    }
    .font-14{
      font-size: 14px;
    }
  }
}
</style>
